package com.xiaomazi.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import com.xiaomazi.common.utils.JwtUtils;
import com.xiaomazi.common.utils.R;
import com.xiaomazi.order.client.CourseClient;
import com.xiaomazi.order.client.UserClient;
import com.xiaomazi.servicebase.entity.CourseInfoToOrder;
import com.xiaomazi.servicebase.entity.UserInfoToOrder;
import com.xiaomazi.servicebase.exception.LLXYException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaomazi.order.entity.Order;
import com.xiaomazi.order.mapper.OrderMapper;
import com.xiaomazi.order.service.OrderService;
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService{

    @Autowired
    private UserClient userClient;

    @Autowired
    private CourseClient courseClient;

    /**
     * 根据课程id生成订单号
     * @param courseId 课程id
     * @return 订单号
     */
    @Override
    public R createOrder(String courseId,String userId) {
        Order order = new Order();
        String orderId = UUID.fastUUID().toString(true);
        order.setOrderNo(orderId);
        CourseInfoToOrder courseToOrderByCourseId = courseClient.getCourseToOrderByCourseId(courseId);
        UserInfoToOrder userInfoToOrderByUserId = userClient.getUserInfoToOrderByUserId(userId);
        if (courseToOrderByCourseId == null || userInfoToOrderByUserId == null){
            throw new LLXYException(20001,"创建订单失败");
        }
        order.setCourseId(courseToOrderByCourseId.getId());
        order.setCourseTitle(courseToOrderByCourseId.getTitle());
        order.setCourseCover(courseToOrderByCourseId.getCover());
        order.setTotalFee(courseToOrderByCourseId.getTotalFee());
        order.setTeacherName(courseToOrderByCourseId.getTeacherName());
        order.setMemberId(userInfoToOrderByUserId.getMemberId());
        order.setNickname(userInfoToOrderByUserId.getNickname());
        order.setMobile(userInfoToOrderByUserId.getMobile());
        this.save(order);
        return R.ok().data("orderId",orderId);
    }

    /**
     * 根据订单号查询订单
     * @param orderId 订单号
     * @return Order
     */
    @Override
    public R getOrderByOrderId(String orderId) {
        return R.ok().data("orderInfo",this.query().eq("order_no",orderId).one());
    }

    /**
     * 根据课程id和用户id查询订单表中订单状态
     * @param courseId 课程id
     * @param memberId 用户id
     * @return boolean
     */
    @Override
    public boolean isBuyCourse(String courseId, String memberId) {
        return this.query().eq("course_id",courseId).eq("member_id",memberId).eq("status",1).count() > 0;
    }
}
